﻿using DeviceAlarmService.SystemService;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json;

namespace DeviceAlarmService.MessagePush.Communication
{
    public class SocketCommunication : ICommunication
    {
        private object Lock = new();
        Socket socket;

        public bool IsConnected => false;

        public void SendSMS(string phone, string message, out string results)
        {
            string str_Content = phone + ":0:" + message;
            //2）编码方式：
            //取值‘0’0x30：文本发送，gbk编码格式
            //取值‘1’0x31：二进制数据
            //取值‘3’0x33: tts 语音电话
            //取值‘5’0x35：文本发送 unicde 编码格式 big-endian

            lock (Lock)
            {
                // 要发送的数据  
                byte[] data = Encoding.Default.GetBytes(str_Content);
                // 发送数据  
                socket.Send(data);
                // 接收来自服务器的响应  
                byte[] receivedData = new byte[1024];
                int receivedBytes = socket.Receive(receivedData);
                // 将接收到的字节转换为字符串  
                string response = Encoding.Default.GetString(receivedData, 0, receivedBytes);

                results = response;
            }
        }

        public void SendCall(string phone, string message, out string results)
        {
            string str_Content = phone + ":3:" + message;
            //2）编码方式：
            //取值‘0’0x30：文本发送，gbk编码格式
            //取值‘1’0x31：二进制数据
            //取值‘3’0x33: tts 语音电话
            //取值‘5’0x35：文本发送 unicde 编码格式 big-endian

            lock (Lock)
            {
                // 要发送的数据  
                byte[] data = Encoding.Default.GetBytes(str_Content);
                // 发送数据  
                socket.Send(data);
                // 接收来自服务器的响应  
                byte[] receivedData = new byte[1024];
                int receivedBytes = socket.Receive(receivedData);
                // 将接收到的字节转换为字符串  
                string response = Encoding.Default.GetString(receivedData, 0, receivedBytes);

                results = response;
            }
        }

        public bool Connect()
        {
            Models.Message.SocketCommunication socketCommunication = JsonSerializer.Deserialize<Models.Message.SocketCommunication>(ConfigService.Configuration.passagewayMessage);
            //创建TCP/IP Socket  
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                // 连接到服务器  
                socket.Connect(new IPEndPoint(IPAddress.Parse(socketCommunication.ip), socketCommunication.port));

                return true;

            }
            catch (Exception)
            {
                return false;
            }
        }

        public void Disconnect()
        {
            if (socket.Connected)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
        }

    }
}
